package com.example.exercise;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.exercise.Base.User;
import com.example.exercise.MysqlUtil.DBService;
import com.example.exercise.MysqlUtil.FindExist;

import java.util.List;

public class LostCard extends AppCompatActivity {

    private  TextView cardid,newcardid,state,message;
    private  EditText name,classroom;
    private  ImageView load,replace,lost;
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lost_card);
        InitView();
        cardread();

        replace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.getText().toString().trim().equals("") || classroom.getText().toString().trim().equals("") || cardid.getText().toString().trim().equals("") || state.getText().toString().trim().equals("")) {

                    message.setText("请先查询");
                } else {

                    if (newcardid.getText().toString().trim().equals("")) {

                        message.setText("请读取新卡号");
                    } else {

                        if (state.getText().toString().trim().equals("否")) {
                            message.setText("该卡没有挂失，请重试");

                        } else {

                            new Thread(new Runnable() {
                                @Override
                                public void run() {


                                    if (FindExist.getUserCard(newcardid.getText().toString()) != 0) {

                                        message.setText("新卡号已存在，请检查");
                                        Looper.prepare();
                                        Toast.makeText(getApplicationContext(), "新卡号已存在，请检查", Toast.LENGTH_SHORT).show();
                                        Looper.loop();

                                    } else {

                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (DBService.UpdateUserCard(name.getText().toString().trim(), classroom.getText().toString().trim(), "否", newcardid.getText().toString().trim()) == 1) {
                                                    message.setText("更新成功");
                                                    Looper.prepare();
                                                    showSuccessDialog();
                                                    Looper.loop();
                                                } else {
                                                    message.setText("更新失败，未知错误");
                                                }
                                            }
                                        }).start();

                                    }

                                }
                            }).start();
                        }

                    }
                }
            }
        });
        load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.getText().toString().trim().equals("")){

                    Toast.makeText(getApplicationContext(),"不能为空",Toast.LENGTH_SHORT).show();
                }else {


                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            final User user;
                            final List<User> list = DBService.getUserCard(name.getText().toString(),classroom.getText().toString());

                            if (list.size() == 0){

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        message.setText("无记录");
                                    }
                                });
                                Looper.prepare();
                                Toast.makeText(getApplicationContext(), "此卡号数据库无记录", Toast.LENGTH_SHORT).show();
                                Looper.loop();


                            }else {
                                user = list.get(0);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "查询成功", Toast.LENGTH_SHORT).show();
                                        message.setText("查询成功");
                                        System.out.println(list.size() + "444");
                                        cardid.setText(user.getCardid());
                                        state.setText(user.getGuashi());
                                    }
                                });

                            }


                        }
                    }).start();
                }
            }
        });

        lost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (state.getText().toString().trim().equals("")|| cardid.getText().toString().trim().equals("")){
                    message.setText("请先查询");
                }else{
                    if (state.getText().toString().trim().equals("否")){
                        showLostDialog();
                    }else {
                        showReLostDialog();
                    }
                }


            }
        });
    }

    private void showReLostDialog() {

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(LostCard.this);
        normalDialog.setTitle("取消挂失提示");
        normalDialog.setMessage("是否取消挂失！！！");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (DBService.LoseState(name.getText().toString().trim(),classroom.getText().toString().trim(),"否") == 1)
                                {
                                    // Toast.makeText(getApplicationContext(), "更新状态成功，请重新查询", Toast.LENGTH_SHORT).show();
                                    message.setText("更新状态成功，请重新查询");
                                    cardid.setText("");
                                    state.setText("");

                                }else{
                                    //Toast.makeText(getApplicationContext(), "更新状态失败", Toast.LENGTH_SHORT).show();
                                    message.setText("更新状态失败，未知错误");
                                    cardid.setText("");
                                    state.setText("");
                                }

                            }
                        }).start();

                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                    }
                });
        // 显示
        normalDialog.show();
    }

    private void showSuccessDialog() {

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(LostCard.this);
        normalDialog.setTitle("成功提示");
        normalDialog.setMessage("卡号已成功更新，挂失状态已取消，是否返回查询页查询");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(getApplicationContext(),Cardjoin.class);
                        startActivity(intent);
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                    }
                });
        // 显示
        normalDialog.show();
    }

    private void showLostDialog() {

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(LostCard.this);
        normalDialog.setTitle("挂失提示");
        normalDialog.setMessage("是否选择挂失！！！");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (DBService.LoseState(name.getText().toString().trim(),classroom.getText().toString().trim(),"是") == 1)
                                {
                                   // Toast.makeText(getApplicationContext(), "更新状态成功，请重新查询", Toast.LENGTH_SHORT).show();
                                    message.setText("更新状态成功，请重新查询");
                                    cardid.setText("");
                                    state.setText("");

                                }else{
                                    //Toast.makeText(getApplicationContext(), "更新状态失败", Toast.LENGTH_SHORT).show();
                                    message.setText("更新状态失败，未知错误");
                                    cardid.setText("");
                                    state.setText("");
                                }

                            }
                        }).start();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do

                    }
                });
        // 显示
        normalDialog.show();
    }

    private void InitView() {
        cardid = findViewById(R.id.gcard);
        newcardid = findViewById(R.id.newid);
        state = findViewById(R.id.gstate);
        name = findViewById(R.id.gname);
        classroom = findViewById(R.id.gclass);
        load =  findViewById(R.id.esearch1);
        replace = findViewById(R.id.recard);
        lost = findViewById(R.id.enterguashi);
        message = findViewById(R.id.textView29);
    }

    private void cardread() {

        //获取默认的NFC控制器
        //初始化NfcAdapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(getApplicationContext(), "设备不支持NFC!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mNfcAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        //初始化PendingIntent
        // 初始化PendingIntent，当有NFC设备连接上的时候，就交给当前Activity处理
        pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    //启动
    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
    }

    //解析
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String CardId =ByteArrayToHexString(tagFromIntent.getId());
        newcardid.setText(CardId);
        Toast.makeText(getApplicationContext(), CardId, Toast.LENGTH_LONG).show();
    }

    //转为16进制字符串
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";


        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);

    }
}